/**
 * 简谱打谱软件 - 主应用逻辑
 */
document.addEventListener('DOMContentLoaded', () => {
  // 初始化应用
  initApp();
  
  // 初始化UI组件
  initUIComponents();
  
  // 初始化事件监听
  initEventListeners();
  
  // 加载已保存的项目
  loadProjects();
});

// 应用状态
const appState = {
  currentProject: null,
  bars: [],
  lyrics: [],
  currentZoom: 80,
  initialized: false
};

// 初始化应用
function initApp() {
  // 从本地存储加载项目列表
  const savedProjects = loadSavedProjects();
  appState.savedProjects = savedProjects || [];
  
  // 初始化基本信息表单
  renderBasicInfoForm();
  
  // 初始化简谱输入区域
  renderSheetInputArea();
  
  // 初始化预览区域
  renderPreviewArea();
  
  appState.initialized = true;
}

// 初始化UI组件
function initUIComponents() {
  // 初始化速度滑块
  const tempoSlider = document.getElementById('tempo');
  const tempoValue = document.getElementById('tempo-value');
  
  tempoSlider.addEventListener('input', () => {
    tempoValue.textContent = `${tempoSlider.value} BPM`;
    updatePreviewMetadata();
  });
  
  // 初始化音符输入键盘
  initNotePad();
}

// 初始化事件监听
function initEventListeners() {
  // 按钮事件
  document.getElementById('new-btn').addEventListener('click', handleNewProject);
  document.getElementById('save-btn').addEventListener('click', handleSaveProject);
  document.getElementById('projects-btn').addEventListener('click', handleOpenProjects);
  document.getElementById('export-btn').addEventListener('click', handleExportPDF);
  document.getElementById('import-btn').addEventListener('click', handleOpenImportModal);
  
  // 缩放控制
  document.getElementById('zoom-in-btn').addEventListener('click', handleZoomIn);
  document.getElementById('zoom-out-btn').addEventListener('click', handleZoomOut);
  document.getElementById('reset-zoom-btn').addEventListener('click', handleResetZoom);
  
  // 对话框关闭事件
  document.getElementById('close-projects-btn').addEventListener('click', closeProjectsModal);
  document.getElementById('close-projects-modal-btn').addEventListener('click', closeProjectsModal);
  document.getElementById('cancel-save-btn').addEventListener('click', closeSaveModal);
  document.getElementById('confirm-save-btn').addEventListener('click', confirmSaveProject);
  document.getElementById('cancel-export-btn').addEventListener('click', closeExportModal);
  document.getElementById('confirm-export-btn').addEventListener('click', confirmExportPDF);
  document.getElementById('cancel-import-btn').addEventListener('click', closeImportModal);
  document.getElementById('import-file').addEventListener('change', handleFileSelect);
  document.getElementById('confirm-import-btn').addEventListener('click', confirmImportProject);
}

// 渲染基本信息表单
function renderBasicInfoForm() {
  const basicInfoContainer = document.getElementById('basic-info');
  
  basicInfoContainer.innerHTML = `
    <h2 class="text-lg font-semibold mb-3 flex items-center">
      <i class="fa fa-info-circle text-primary mr-2"></i> 基本信息
    </h2>
    <div class="space-y-3">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">曲名</label>
        <input type="text" id="song-title" class="input-field" placeholder="请输入曲名">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">作曲</label>
        <input type="text" id="composer" class="input-field" placeholder="请输入作曲者">
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">作词</label>
        <input type="text" id="lyricist" class="input-field" placeholder="请输入作词者">
      </div>
      <div class="grid grid-cols-2 gap-3">
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">调号</label>
          <select id="key-signature" class="input-field">
            <option value="C">C调</option>
            <option value="D">D调</option>
            <option value="E">E调</option>
            <option value="F">F调</option>
            <option value="G">G调</option>
            <option value="A">A调</option>
            <option value="B">B调</option>
          </select>
        </div>
        <div>
          <label class="block text-sm font-medium text-gray-700 mb-1">拍号</label>
          <select id="time-signature" class="input-field">
            <option value="2/4">2/4</option>
            <option value="3/4">3/4</option>
            <option value="4/4">4/4</option>
            <option value="3/8">3/8</option>
            <option value="6/8">6/8</option>
          </select>
        </div>
      </div>
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">速度</label>
        <div class="flex items-center">
          <input type="range" id="tempo" min="40" max="200" value="120" class="w-full h-2 bg-gray-200 rounded-lg appearance-none cursor-pointer">
          <span id="tempo-value" class="ml-2 text-sm font-medium">120 BPM</span>
        </div>
      </div>
    </div>
  `;
  
  // 添加表单输入事件监听
  document.getElementById('song-title').addEventListener('input', updatePreviewMetadata);
  document.getElementById('composer').addEventListener('input', updatePreviewMetadata);
  document.getElementById('lyricist').addEventListener('input', updatePreviewMetadata);
  document.getElementById('key-signature').addEventListener('change', updatePreviewMetadata);
  document.getElementById('time-signature').addEventListener('change', updatePreviewMetadata);
}

// 渲染简谱输入区域
function renderSheetInputArea() {
  const sheetInputContainer = document.getElementById('sheet-input');
  
  sheetInputContainer.innerHTML = `
    <h2 class="text-lg font-semibold mb-3 flex items-center">
      <i class="fa fa-pencil text-primary mr-2"></i> 简谱输入
    </h2>
    
    <div class="space-y-3">
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">歌词</label>
        <textarea id="lyrics" rows="4" class="input-field" placeholder="请输入歌词，每行一句"></textarea>
      </div>
      
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">简谱符号</label>
        <div class="grid grid-cols-7 gap-2 mb-3" id="note-pad">
          <!-- 音符按钮将由JavaScript动态生成 -->
        </div>
      </div>
      
      <div>
        <label class="block text-sm font-medium text-gray-700 mb-1">当前小节</label>
        <div id="current-bar" class="flex flex-wrap gap-1 p-2 border rounded min-h-[40px]">
          <span class="text-gray-400">点击上方音符添加...</span>
        </div>
      </div>
      
      <div class="flex justify-between space-x-2">
        <button id="add-bar-btn" class="btn btn-primary flex-1">
          <i class="fa fa-plus mr-1"></i> 添加小节
        </button>
        <button id="clear-bar-btn" class="btn btn-outline">
          <i class="fa fa-trash-o mr-1"></i> 清空
        </button>
      </div>
    </div>
  `;
  
  // 添加事件监听
  document.getElementById('add-bar-btn').addEventListener('click', handleAddBar);
  document.getElementById('clear-bar-btn').addEventListener('click', handleClearBar);
  document.getElementById('lyrics').addEventListener('input', handleLyricsUpdate);
}

// 渲染预览区域
function renderPreviewArea() {
  const previewContainer = document.getElementById('sheet-preview-container');
  
  previewContainer.innerHTML = `
    <div class="flex justify-between items-center mb-4">
      <h2 class="text-lg font-semibold flex items-center">
        <i class="fa fa-eye text-primary mr-2"></i> 简谱预览
      </h2>
      <div class="flex space-x-2">
        <button id="zoom-in-btn" class="p-1.5 rounded hover:bg-gray-100 transition-colors">
          <i class="fa fa-search-plus text-neutral-dark"></i>
        </button>
        <button id="zoom-out-btn" class="p-1.5 rounded hover:bg-gray-100 transition-colors">
          <i class="fa fa-search-minus text-neutral-dark"></i>
        </button>
        <button id="reset-zoom-btn" class="p-1.5 rounded hover:bg-gray-100 transition-colors">
          <i class="fa fa-refresh text-neutral-dark"></i>
        </button>
      </div>
    </div>
    
    <div id="sheet-preview" class="bg-white p-6 border border-gray-200 rounded-lg overflow-auto min-h-[700px] max-w-4xl mx-auto" style="zoom: 80%">
      <div id="sheet-content" class="font-mono">
        <div class="text-center mb-6">
          <h1 id="preview-title" class="text-2xl font-bold mb-1">歌曲标题</h1>
          <div class="flex justify-center space-x-6 text-sm text-gray-600 mb-2">
            <span>作曲：<span id="preview-composer">作曲者</span></span>
            <span>作词：<span id="preview-lyricist">作词者</span></span>
          </div>
          <div class="flex justify-center space-x-4 text-sm text-gray-600">
            <span id="preview-key">1=C</span>
            <span id="preview-time">4/4</span>
            <span id="preview-tempo">♩=120</span>
          </div>
        </div>
        
        <div id="preview-bars" class="space-y-6">
          <div class="text-center text-gray-400 italic py-12">
            请从左侧面板添加简谱内容...
          </div>
        </div>
        
        <div id="preview-lyrics" class="mt-10 pt-4 border-t border-gray-200">
          <h3 class="text-lg font-semibold mb-3 text-center">歌词</h3>
          <div id="lyrics-display" class="text-center space-y-2">
            <div class="text-gray-400 italic">请输入歌词...</div>
          </div>
        </div>
      </div>
    </div>
  `;
}

// 初始化音符输入键盘
function initNotePad() {
  const notePad = document.getElementById('note-pad');
  
  // 音符数据
  const noteData = [
    ['1', '2', '3', '4', '5', '6', '7'],
    ['·1', '·2', '·3', '·4', '·5', '·6', '·7'],
    ['1·', '2·', '3·', '4·', '5·', '6·', '7·'],
    ['0', '|', '||', '∥', '·', '-', '_']
  ];
  
  // 生成音符按钮
  let noteHtml = '';
  noteData.forEach(row => {
    row.forEach(note => {
      // 处理上下加点的显示
      let displayNote = note;
      if (note.startsWith('·')) {
        displayNote = `<sup>${note[1]}</sup>${note.slice(2)}`;
      } else if (note.endsWith('·')) {
        displayNote = `${note.slice(0, -1)}<sub>${note[note.length-2]}</sub>`;
      }
      
      noteHtml += `
        <button class="note-btn p-2 border rounded text-center hover:bg-gray-100 transition-colors" data-value="${note}">
          ${displayNote}
        </button>
      `;
    });
  });
  
  notePad.innerHTML = noteHtml;
  
  // 添加点击事件
  notePad.addEventListener('click', (e) => {
    if (e.target.classList.contains('note-btn')) {
      const note = e.target.dataset.value;
      addNoteToCurrentBar(note);
    }
  });
}

// 添加音符到当前小节
function addNoteToCurrentBar(note) {
  const currentBar = document.getElementById('current-bar');
  
  // 清除提示文本
  if (currentBar.querySelector('.text-gray-400')) {
    currentBar.innerHTML = '';
  }
  
  // 创建音符元素
  const noteElement = document.createElement('div');
  noteElement.className = 'note-input bg-white';
  noteElement.textContent = note;
  noteElement.dataset.value = note;
  noteElement.dataset.id = Date.now() + '-' + Math.random().toString(36).substring(2, 10);
  
  // 添加编辑功能
  noteElement.addEventListener('dblclick', () => {
    const editInput = document.createElement('input');
    editInput.type = 'text';
    editInput.value = note;
    editInput.className = 'w-full text-center border-none focus:ring-0';
    
    // 替换音符元素为输入框
    noteElement.innerHTML = '';
    noteElement.appendChild(editInput);
    editInput.focus();
    
    // 失去焦点或按下Enter时保存编辑
    editInput.addEventListener('blur', () => {
      saveNoteEdit(noteElement, editInput);
    });
    
    editInput.addEventListener('keydown', (e) => {
      if (e.key === 'Enter') {
        saveNoteEdit(noteElement, editInput);
      }
    });
  });
  
  currentBar.appendChild(noteElement);
  
  // 自动聚焦到新添加的音符
  noteElement.focus();
}

// 保存音符编辑
function saveNoteEdit(noteElement, editInput) {
  const newNote = editInput.value.trim();
  if (newNote) {
    noteElement.dataset.value = newNote;
    noteElement.textContent = newNote;
  }
}

// 处理添加小节
function handleAddBar() {
  const currentBar = document.getElementById('current-bar');
  const notes = Array.from(currentBar.querySelectorAll('.note-input')).map(note => note.dataset.value);
  
  if (notes.length === 0) {
    showNotification('当前小节为空，请添加音符后再试！', 'error');
    return;
  }
  
  // 添加到小节列表
  appState.bars.push(notes);
  
  // 更新预览
  updatePreview();
  
  // 清空当前小节
  currentBar.innerHTML = '<span class="text-gray-400">点击上方音符添加...</span>';
  
  // 显示成功通知
  showNotification('小节已添加！', 'success');
}

// 处理清空当前小节
function handleClearBar() {
  const currentBar = document.getElementById('current-bar');
  currentBar.innerHTML = '<span class="text-gray-400">点击上方音符添加...</span>';
}

// 处理歌词更新
function handleLyricsUpdate() {
  const lyricsText = document.getElementById('lyrics').value;
  appState.lyrics = lyricsText.split('\n').filter(line => line.trim() !== '');
  updateLyricsPreview();
}

// 更新预览元数据
function updatePreviewMetadata() {
  const title = document.getElementById('song-title').value || '歌曲标题';
  const composer = document.getElementById('composer').value || '作曲者';
  const lyricist = document.getElementById('lyricist').value || '作词者';
  const key = document.getElementById('key-signature').value;
  const time = document.getElementById('time-signature').value;
  const tempo = document.getElementById('tempo').value;
  
  document.getElementById('preview-title').textContent = title;
  document.getElementById('preview-composer').textContent = composer;
  document.getElementById('preview-lyricist').textContent = lyricist;
  document.getElementById('preview-key').textContent = `1=${key}`;
  document.getElementById('preview-time').textContent = time;
  document.getElementById('preview-tempo').textContent = `♩=${tempo}`;
}

// 更新简谱预览
function updatePreview() {
  updatePreviewMetadata();
  
  const previewBars = document.getElementById('preview-bars');
  
  // 如果没有小节，显示提示信息
  if (appState.bars.length === 0) {
    previewBars.innerHTML = `
      <div class="text-center text-gray-400 italic py-12">
        请从左侧面板添加简谱内容...
      </div>
    `;
    return;
  }
  
  // 生成小节HTML
  let barsHtml = '';
  
  appState.bars.forEach((bar, index) => {
    // 每5个小节换行
    if (index > 0 && index % 5 === 0) {
      barsHtml += '<div class="my-4"></div>';
    }
    
    // 生成小节中的音符
    let notesHtml = '';
    bar.forEach(note => {
      // 处理上下加点
      let displayNote = note;
      if (note.startsWith('·')) {
        displayNote = `<sup>${note[1]}</sup>${note.slice(2)}`;
      } else if (note.endsWith('·')) {
        displayNote = `${note.slice(0, -1)}<sub>${note[note.length-2]}</sub>`;
      }
      
      notesHtml += `<span class="inline-block px-1.5">${displayNote}</span>`;
    });
    
    barsHtml += `
      <div class="inline-block mr-2 last:mr-0 relative" data-index="${index}">
        <div class="flex flex-col items-center">
          <div class="sheet-line w-full"></div>
          <div class="sheet-line w-full"></div>
          <div class="sheet-line w-full"></div>
          <div class="sheet-line w-full"></div>
          <div class="mt-1 text-center">${notesHtml}</div>
        </div>
        <div class="absolute -top-6 right-0 opacity-0 hover:opacity-100 transition-opacity">
          <button class="edit-bar-btn text-blue-500 hover:text-blue-700" title="编辑">
            <i class="fa fa-pencil"></i>
          </button>
          <button class="delete-bar-btn text-red-500 hover:text-red-700 ml-1" title="删除">
            <i class="fa fa-trash-o"></i>
          </button>
        </div>
      </div>
    `;
  });
  
  previewBars.innerHTML = barsHtml;
  
  // 添加小节编辑和删除事件
  document.querySelectorAll('.edit-bar-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const barIndex = parseInt(e.target.closest('[data-index]').dataset.index);
      editBar(barIndex);
    });
  });
  
  document.querySelectorAll('.delete-bar-btn').forEach(btn => {
    btn.addEventListener('click', (e) => {
      const barIndex = parseInt(e.target.closest('[data-index]').dataset.index);
      deleteBar(barIndex);
    });
  });
  
  // 更新歌词预览
  updateLyricsPreview();
}

// 更新歌词预览
function updateLyricsPreview() {
  const lyricsDisplay = document.getElementById('lyrics-display');
  
  if (appState.lyrics.length === 0) {
    lyricsDisplay.innerHTML = `<div class="text-gray-400 italic">请输入歌词...</div>`;
    return;
  }
  
  let lyricsHtml = '';
  appState.lyrics.forEach(line => {
    lyricsHtml += `<div class="lyric-line">${line}</div>`;
  });
  
  lyricsDisplay.innerHTML = lyricsHtml;
}

// 编辑小节
function editBar(index) {
  if (index >= 0 && index < appState.bars.length) {
    const barNotes = appState.bars[index];
    const currentBar = document.getElementById('current-bar');
    
    // 清空当前小节
    currentBar.innerHTML = '';
    
    // 添加音符到当前小节
    barNotes.forEach(note => {
      addNoteToCurrentBar(note);
    });
    
    // 从列表中删除该小节
    appState.bars.splice(index, 1);
    
    // 更新预览
    updatePreview();
    
    // 显示编辑提示
    showNotification(`正在编辑第 ${index + 1} 小节`, 'info');
  }
}

// 删除小节
function deleteBar(index) {
  if (index >= 0 && index < appState.bars.length) {
    if (confirm(`确定要删除第 ${index + 1} 小节吗？`)) {
      appState.bars.splice(index, 1);
      updatePreview();
      showNotification(`已删除第 ${index + 1} 小节`, 'info');
    }
  }
}

// 处理新建项目
function handleNewProject() {
  if (appState.bars.length > 0 || document.getElementById('song-title').value.trim() !== '') {
    if (!confirm('当前项目有未保存的更改，确定要创建新项目吗？')) {
      return;
    }
  }
  
  // 重置应用状态
  appState.currentProject = null;
  appState.bars = [];
  appState.lyrics = [];
  
  // 重置表单
  document.getElementById('song-title').value = '';
  document.getElementById('composer').value = '';
  document.getElementById('lyricist').value = '';
  document.getElementById('key-signature').value = 'C';
  document.getElementById('time-signature').value = '4/4';
  document.getElementById('tempo').value = 120;
  document.getElementById('tempo-value').textContent = '120 BPM';
  document.getElementById('lyrics').value = '';
  
  // 清空当前小节
  document.getElementById('current-bar').innerHTML = '<span class="text-gray-400">点击上方音符添加...</span>';
  
  // 更新预览
  updatePreview();
  
  // 显示通知
  showNotification('已创建新项目！', 'success');
}

// 处理保存项目
function handleSaveProject() {
  // 检查是否有内容
  if (appState.bars.length === 0 && document.getElementById('song-title').value.trim() === '') {
    showNotification('项目为空，请先添加内容！', 'error');
    return;
  }
  
  // 显示保存对话框
  document.getElementById('save-project-name').value = document.getElementById('song-title').value || '未命名项目';
  document.getElementById('save-project-description').value = '';
  
  // 显示对话框
  document.getElementById('save-modal').classList.remove('hidden');
  setTimeout(() => {
    document.getElementById('save-modal-content').classList.remove('scale-95', 'opacity-0');
    document.getElementById('save-modal-content').classList.add('scale-100', 'opacity-100');
  }, 10);
}

// 确认保存项目
function confirmSaveProject() {
  const projectName = document.getElementById('save-project-name').value.trim();
  const projectDescription = document.getElementById('save-project-description').value.trim();
  
  if (!projectName) {
    showNotification('请输入项目名称！', 'error');
    return;
  }
  
  // 创建项目数据
  const projectData = {
    id: Date.now().toString(),
    name: projectName,
    description: projectDescription,
    createdAt: new Date().toISOString(),
    updatedAt: new Date().toISOString(),
    data: {
      metadata: {
        title: document.getElementById('song-title').value,
        composer: document.getElementById('composer').value,
        lyricist: document.getElementById('lyricist').value,
        keySignature: document.getElementById('key-signature').value,
        timeSignature: document.getElementById('time-signature').value,
        tempo: document.getElementById('tempo').value
      },
      bars: appState.bars,
      lyrics: appState.lyrics
    }
  };
  
  // 保存项目
  saveProject(projectData);
  
  // 更新应用状态
  appState.currentProject = projectData;
  
  // 关闭对话框
  closeSaveModal();
  
  // 显示成功通知
  showNotification(`项目 "${projectName}" 已保存！`, 'success');
  
  // 刷新项目列表
  loadProjects();
}

// 处理打开项目列表
function handleOpenProjects() {
  loadProjects();
  
  // 显示对话框
  document.getElementById('projects-modal').classList.remove('hidden');
  setTimeout(() => {
    document.getElementById('projects-modal-content').classList.remove('scale-95', 'opacity-0');
    document.getElementById('projects-modal-content').classList.add('scale-100', 'opacity-100');
  }, 10);
}

// 加载项目列表
function loadProjects() {
  const projectsList = document.getElementById('projects-list');
  const projects = loadSavedProjects() || [];
  
  if (projects.length === 0) {
    projectsList.innerHTML = `
      <div class="text-center text-gray-400 py-12">
        暂无保存的项目
      </div>
    `;
    return;
  }
  
  // 按更新时间排序
  projects.sort((a, b) => new Date(b.updatedAt) - new Date(a.updatedAt));
  
  // 生成项目列表
  let projectsHtml = '';
  projects.forEach(project => {
    const createdAt = new Date(project.createdAt).toLocaleString();
    const updatedAt = new Date(project.updatedAt).toLocaleString();
    
    projectsHtml += `
      <div class="p-3 border-b border-gray-100 hover:bg-gray-50 transition-colors project-item" data-id="${project.id}">
        <div class="flex justify-between items-start">
          <div>
            <h4 class="font-medium">${project.name}</h4>
            <p class="text-sm text-gray-500 mt-1">${project.description || '无描述'}</p>
          </div>
          <div class="flex space-x-1">
            <button class="edit-project-btn p-1.5 rounded hover:bg-gray-200 transition-colors" title="编辑">
              <i class="fa fa-pencil text-gray-600"></i>
            </button>
            <button class="delete-project-btn p-1.5 rounded hover:bg-gray-200 transition-colors" title="删除">
              <i class="fa fa-trash-o text-gray-600"></i>
            </button>
            <button class="export-project-btn p-1.5 rounded hover:bg-gray-200 transition-colors" title="导出">
              <i class="fa fa-download text-gray-600"></i>
            </button>
          </div>
        </div>
        <div class="flex justify-between items-center mt-2 text-xs text-gray-400">
          <span>创建于: ${createdAt}</span>
          <span>更新于: ${updatedAt}</span>
        </div>
      </div>
    `;
  });
  
  projectsList.innerHTML = projectsHtml;
  
  // 添加项目操作事件
  document.querySelectorAll('.project-item').forEach(item => {
    item.addEventListener('click', (e) => {
      if (!e.target.closest('button')) {
        const projectId = item.dataset.id;
        loadProject(projectId);
        closeProjectsModal();
      }
    });
    
    // 编辑项目
    item.querySelector('.edit-project-btn').addEventListener('click', (e) => {
      e.stopPropagation();
      const projectId = item.dataset.id;
      editProjectMetadata(projectId);
    });
    
    // 删除项目
    item.querySelector('.delete-project-btn').addEventListener('click', (e) => {
      e.stopPropagation();
      const projectId = item.dataset.id;
      deleteProject(projectId);
    });
    
    // 导出项目
    item.querySelector('.export-project-btn').addEventListener('click', (e) => {
      e.stopPropagation();
      const projectId = item.dataset.id;
      exportProjectToFile(projectId);
    });
  });
}

// 加载项目
function loadProject(projectId) {
  const projects = loadSavedProjects() || [];
  const project = projects.find(p => p.id === projectId);
  
  if (!project) {
    showNotification('项目不存在！', 'error');
    return;
  }
  
  // 加载项目数据
  const { metadata, bars, lyrics } = project.data;
  
  // 更新表单
  document.getElementById('song-title').value = metadata.title || '';
  document.getElementById('composer').value = metadata.composer || '';
  document.getElementById('lyricist').value = metadata.lyricist || '';
  document.getElementById('key-signature').value = metadata.keySignature || 'C';
  document.getElementById('time-signature').value = metadata.timeSignature || '4/4';
  document.getElementById('tempo').value = metadata.tempo || 120;
  document.getElementById('tempo-value').textContent = `${metadata.tempo || 120} BPM`;
  document.getElementById('lyrics').value = lyrics.join('\n');
  
  // 更新应用状态
  appState.currentProject = project;
  appState.bars = bars || [];
  appState.lyrics = lyrics || [];
  
  // 清空当前小节
  document.getElementById('current-bar').innerHTML = '<span class="text-gray-400">点击上方音符添加...</span>';
  
  // 更新预览
  updatePreview();
  
  // 显示通知
  showNotification(`已加载项目 "${project.name}"`, 'success');
}

// 编辑项目元数据
function editProjectMetadata(projectId) {
  const projects = loadSavedProjects() || [];
  const project = projects.find(p => p.id === projectId);
  
  if (!project) {
    showNotification('项目不存在！', 'error');
    return;
  }
  
  // 填充表单
  document.getElementById('save-project-name').value = project.name;
  document.getElementById('save-project-description').value = project.description || '';
  
  // 显示对话框
  document.getElementById('save-modal').classList.remove('hidden');
  setTimeout(() => {
    document.getElementById('save-modal-content').classList.remove('scale-95', 'opacity-0');
    document.getElementById('save-modal-content').classList.add('scale-100', 'opacity-100');
  }, 10);
  
  // 覆盖保存按钮事件
  const saveBtn = document.getElementById('confirm-save-btn');
  const originalSaveHandler = saveBtn.onclick;
  
  saveBtn.onclick = () => {
    // 恢复原始事件
    saveBtn.onclick = originalSaveHandler;
    
    // 更新项目元数据
    const newName = document.getElementById('save-project-name').value.trim();
    const newDescription = document.getElementById('save-project-description').value.trim();
    
    if (!newName) {
      showNotification('请输入项目名称！', 'error');
      return;
    }
    
    project.name = newName;
    project.description = newDescription;
    project.updatedAt = new Date().toISOString();
    
    // 保存更新
    saveProject(project);
    
    // 关闭对话框
    closeSaveModal();
    
    // 显示成功通知
    showNotification(`项目 "${newName}" 已更新！`, 'success');
    
    // 刷新项目列表
    loadProjects();
  };
}

// 删除项目
function deleteProject(projectId) {
  if (confirm('确定要删除这个项目吗？此操作不可撤销！')) {
    const projects = loadSavedProjects() || [];
    const updatedProjects = projects.filter(p => p.id !== projectId);
    
    // 保存更新后的项目列表
    localStorage.setItem('sheetMusicProjects', JSON.stringify(updatedProjects));
    
    // 如果当前正在编辑已删除的项目，则重置
    if (appState.currentProject && appState.currentProject.id === projectId) {
      handleNewProject();
    }
    
    // 刷新项目列表
    loadProjects();
    
    // 显示通知
    showNotification('项目已删除！', 'info');
  }
}

// 处理导出PDF
function handleExportPDF() {
  // 检查是否有内容
  if (appState.bars.length === 0) {
    showNotification('请先添加简谱内容再导出！', 'error');
    return;
  }
  
  // 设置默认文件名
  document.getElementById('pdf-filename').value = document.getElementById('song-title').value || '简谱';
  
  // 显示对话框
  document.getElementById('export-modal').classList.remove('hidden');
  setTimeout(() => {
    document.getElementById('export-modal-content').classList.remove('scale-95', 'opacity-0');
    document.getElementById('export-modal-content').classList.add('scale-100', 'opacity-100');
  }, 10);
}

// 处理打开导入对话框
function handleOpenImportModal() {
  document.getElementById('import-file').value = '';
  document.getElementById('confirm-import-btn').disabled = true;
  
  // 显示对话框
  document.getElementById('import-modal').classList.remove('hidden');
  setTimeout(() => {
    document.getElementById('import-modal-content').classList.remove('scale-95', 'opacity-0');
    document.getElementById('import-modal-content').classList.add('scale-100', 'opacity-100');
  }, 10);
}

// 处理文件选择
function handleFileSelect(e) {
  const file = e.target.files[0];
  if (file) {
    document.getElementById('confirm-import-btn').disabled = false;
  }
}

// 确认导入项目
function confirmImportProject() {
  const fileInput = document.getElementById('import-file');
  const file = fileInput.files[0];
  
  if (!file) {
    showNotification('请选择要导入的文件！', 'error');
    return;
  }
  
  const reader = new FileReader();
  
  reader.onload = (e) => {
    try {
      const fileContent = e.target.result;
      let projectData;
      
      // 根据文件类型解析
      if (file.name.endsWith('.json')) {
        projectData = JSON.parse(fileContent);
      } else if (file.name.endsWith('.xml')) {
        projectData = parseXmlProject(fileContent);
      } else if (file.name.endsWith('.txt')) {
        projectData = parseTextProject(fileContent);
      } else {
        throw new Error('不支持的文件格式！');
      }
      
      // 检查解析结果
      if (!projectData || !projectData.data) {
        throw new Error('文件内容格式不正确！');
      }
      
      // 导入项目
      importProject(projectData);
      
      // 关闭对话框
      closeImportModal();
      
      // 显示成功通知
      showNotification(`已导入项目 "${projectData.name || '未命名'}"`, 'success');
      
      // 刷新项目列表
      loadProjects();
    } catch (error) {
      console.error('导入失败:', error);
      showNotification(`导入失败: ${error.message}`, 'error');
    }
  };
  
  reader.readAsText(file);
}

// 处理缩放相关操作
function handleZoomIn() {
  if (appState.currentZoom < 150) {
    appState.currentZoom += 10;
    document.getElementById('sheet-preview').style.zoom = `${appState.currentZoom}%`;
  }
}

function handleZoomOut() {
  if (appState.currentZoom > 50) {
    appState.currentZoom -= 10;
    document.getElementById('sheet-preview').style.zoom = `${appState.currentZoom}%`;
  }
}

function handleResetZoom() {
  appState.currentZoom = 80;
  document.getElementById('sheet-preview').style.zoom = `${appState.currentZoom}%`;
}

// 显示通知
function showNotification(message, type = 'info') {
  // 创建通知元素
  const notification = document.createElement('div');
  notification.className = `fixed top-4 right-4 px-4 py-2 rounded-md shadow-lg transform transition-all duration-300 translate-x-full opacity-0 z-50 ${
    type === 'success' ? 'bg-green-500 text-white' : 
    type === 'error' ? 'bg-red-500 text-white' : 
    'bg-blue-500 text-white'
  }`;
  notification.innerHTML = `
    <div class="flex items-center">
      <i class="fa ${
        type === 'success' ? 'fa-check-circle' : 
        type === 'error' ? 'fa-exclamation-circle' : 
        'fa-info-circle'
      } mr-2"></i>
      <span>${message}</span>
    </div>
  `;
  
  // 添加到页面
  document.body.appendChild(notification);
  
  // 显示通知
  setTimeout(() => {
    notification.classList.remove('translate-x-full', 'opacity-0');
    notification.classList.add('translate-x-0', 'opacity-100');
  }, 10);
  
  // 自动关闭
  setTimeout(() => {
    notification.classList.remove('translate-x-0', 'opacity-100');
    notification.classList.add('translate-x-full', 'opacity-0');
    
    // 移除元素
    setTimeout(() => {
      document.body.removeChild(notification);
    }, 300);
  }, 3000);
}

// 关闭各种模态框
function closeSaveModal() {
  const modalContent = document.getElementById('save-modal-content');
  const modal = document.getElementById('save-modal');
  
  modalContent.classList.remove('scale-100', 'opacity-100');
  modalContent.classList.add('scale-95', 'opacity-0');
  setTimeout(() => {
    modal.classList.add('hidden');
  }, 300);
}

function closeProjectsModal() {
  const modalContent = document.getElementById('projects-modal-content');
  const modal = document.getElementById('projects-modal');
  
  modalContent.classList.remove('scale-100', 'opacity-100');
  modalContent.classList.add('scale-95', 'opacity-0');
  setTimeout(() => {
    modal.classList.add('hidden');
  }, 300);
}

function closeExportModal() {
  const modalContent = document.getElementById('export-modal-content');
  const modal = document.getElementById('export-modal');
  
  modalContent.classList.remove('scale-100', 'opacity-100');
  modalContent.classList.add('scale-95', 'opacity-0');
  setTimeout(() => {
    modal.classList.add('hidden');
  }, 300);
}

function closeImportModal() {
  const modalContent = document.getElementById('import-modal-content');
  const modal = document.getElementById('import-modal');
  
  modalContent.classList.remove('scale-100', 'opacity-100');
  modalContent.classList.add('scale-95', 'opacity-0');
  setTimeout(() => {
    modal.classList.add('hidden');
  }, 300);
}
    